package com.pengliu.util;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;



/*简单类似于redis的缓存*/
public class CacheMap{
	
	private static LinkedHashMap<String, Object> cacheMap = new LinkedHashMap<String, Object>();
	
	//缓存峰值
	public static int size = 1000;
	
	public static void putKV(String key,Object value){
		putKV(key, value, null);
	}
	
	public static void putKV(String key,Object value,Long milliSecond){
		if(size==cacheMap.size()){
			Set<String> keySet = cacheMap.keySet();
            Iterator<String> iterator = keySet.iterator();
            String firstKey = "";                
            if (iterator.hasNext()) {
                firstKey = iterator.next();
            }
            if(!"".equals(firstKey)){
            	cacheMap.remove(firstKey);
            }
		}
		
		cacheMap.put(key, value);
		
		//失效时间设置
		if(null != milliSecond) {
			Timer timer= new Timer();
	        TimerTask task  = new TimerTask(){    //创建一个新的计时器任务。
	           @Override
	           public void run() {
	        	  cacheMap.remove(key);
	           } 
	        };
	        timer.schedule(task, milliSecond-System.currentTimeMillis());
		}
	}
	
	public static Object getValue(String key){
		return cacheMap.get(key);
	}
	
	public static void remove(String key) {
		if(cacheMap.containsKey(key)) {
			cacheMap.remove(key);
		}
	}
	
	private LinkedHashMap<String, Object> getListMap(){
		LinkedHashMap<String, Object> linkedHashMap =  new LinkedHashMap<String, Object>();
		ListIterator<Map.Entry<String,Object>> i=new ArrayList<Map.Entry<String,Object>>(cacheMap.entrySet()).listIterator(cacheMap.size());
        while(i.hasPrevious()) {
            Map.Entry<String, Object> entry=i.previous();
            linkedHashMap.put(entry.getKey(), entry.getValue());
        }
        return linkedHashMap;
	}
	
	public static void cleanMap(){
		cacheMap.clear();
	}
}
